let initData = {
    shopList: JSON.parse(localStorage.getItem('shopList')) || [],
    allFlag: false
}

let carReducer = (state = initData, {type,payload}) => {
    switch(type) {

        case 'ADD_SHOP':

            let findex = state.shopList.findIndex(item => item.id === payload.id)

            if(findex !== -1) {
                if(state.shopList[findex].count++ >= 5) {
                    window.alert('最多只能买5个')
                    state.shopList[findex].count = 5
                }
            }
            else {
                state.shopList.push(payload)
            }

            localStorage.setItem('shopList', JSON.stringify([...state.shopList]))

            return {
                ...state,
                shopList: [...state.shopList]
            }

        case 'SUBTRACT':

            state.shopList.forEach((item,index) => {
                if(payload === index) {
                    if(item.count-- <= 1) {
                        let flag = window.confirm('确定要删除吗')
                        flag ? state.shopList.splice(index, 1) : item.count = 1
                    }
                }
            })

            localStorage.setItem('shopList', JSON.stringify([...state.shopList]))

            return {
                ...state,
                shopList: [...state.shopList]
            }

        case 'ADD':

            state.shopList.forEach((item,index) => {
                if(payload === index) {
                    if(item.count++ >= 5) {
                        window.confirm('最多只能购买5个')
                        item.count = 5
                    }
                }
            })

            localStorage.setItem('shopList', JSON.stringify([...state.shopList]))

            return {
                ...state,
                shopList: [...state.shopList]
            }

        case 'CHECK_ITEM':

            state.shopList[payload].flag = !state.shopList[payload].flag

            state.allFlag = state.shopList.every(item => item.flag)

            return {
                ...state,
                shopList: [...state.shopList],
                allFlag: state.allFlag
            }

        case 'ALL_CHECK_ITEM':

            state.allFlag = !state.allFlag

            state.shopList.forEach(item => {
                item.flag = state.allFlag
            })

            return {
                ...state,
                allFlag: state.allFlag
            }

        default:
            return {
                ...state
            }
    }
}

export default carReducer